<?php
/**
 * 
 * @author Freezy
 *
 */
class Perbuatan extends MY_Controller {

	function Perbuatan(){
		parent::MY_Controller();
		$this->validate_cookie();
	}
	
	function _remap(){
		//validate user first
		$URICount = $this->uri->total_segments();
		$usr = $this->uri->segment(2);	//get username
		$this->_validateUser($usr);
		
		//call function
		$func = $this->uri->segment(4);
		$params = array();
		for($i=5;$i<=$URICount; $i++){
			$params[] = $this->uri->segment($i);
		}
		
	    if ( method_exists($this, $func) ) {
	    	call_user_func_array( array($this, $func), $params);
	    }
	    else if (count($params)<=0){
			$this->index();
		}
	}
	
	/*********************************
	 * dashboard
	 *********************************/
	
	function index(){
		$this->load->library('session');
		$usrAlias = md5($this->session->userdata('usrname'));
		
		$this->load->helper(array('html'));
		$this->load->config('rnd', true);
		$CONF = $this->config->item('rnd');

		//layout first
		$this->load->model('departemen_model');
		$layoutConf = $CONF['layout'];
		$layoutConf['left_content'] = array(
			'view'=>'template/horz_nav', 
			'view_data'=>array(
				'data'=>$usrAlias!=md5('admin')?$this->_translate_nav($CONF['nav']['users'],$usrAlias):$CONF['nav']['psdm'],
				'title'=>'Laporan Perbuatan'
			) 
		);
		$layoutConf['right_content'] = array('view'=>'perbuatan/users/dashboard', 
			'view_data'=>array(
				'limit' => 5,//tampilkan sedikit saja$CONF['search']['limit'],
				'usrAlias'=>$usrAlias
			));
		$this->initialize_layout($layoutConf);
		
		//page
		$pageConf = $CONF['page'];
		$pageConf['jscript_default'][] = 'users/perbuatan/perbuatan_dashboard';
		$pageConf['jscript'] = $pageConf['jscript_default'];
		$pageConf['css'] = $pageConf['css_default'];
		$pageConf['template_view'] = 'template/2_layout';
		$this->initialize_page($pageConf);
		
		$this->finalize_view();
	}
	
	function _search($type){
		$this->{"__search_$type"}();
	}
	
	function __search_RA(){
		$this->load->library('session');
		$usrName = $this->session->userdata('usrname');
		$usrAlias = md5($usrName);
		
		$this->load->model('perbuatan_model');
		$this->load->config('rnd',true);
		$conf = $this->config->item('rnd');
		$conf1 = $conf['perbuatan']['status'];
		
		//ada kodenya, jadi load config dulu
		$key = $this->input->post('key');
		$keysss = array();
		$keysss[] = $key; 
		if ($ss = array_search(ucwords($key), $conf1)) $keysss[] = $ss;	//key untuk status
		
		$limit = $this->input->post('limit');
		$offset = $this->input->post('offset') * $limit;
		$orderby = $this->input->post('orderby');
		$where = $this->input->post('where');
		
		$table_content = "";
		$row = 0;
		$data = $this->perbuatan_model->getRequestApproval(
			$usrName, $keysss, $where, $limit, $offset, 
			$orderby? $orderby : array('perb_status'=>'desc'));
		$table_content = $this->load->view('perbuatan/users/table_content_RA', array(
			'data'=>$data,
			'status_options'=>$conf1,
			'usrAlias'=>$usrAlias,
			'usrName'=>$usrName
			), true);
		echo json_encode(array(
			'table_content'=>$table_content,
			'table_num_record'=> $key? $data->num_rows() : $this->perbuatan_model->count_record()
		));
	}
	
	function __search_AP(){
		$this->load->library('session');
		$usrName = $this->session->userdata('usrname');
		$usrAlias = md5($usrName);
		
		$this->load->model('perbuatan_model');
		$this->load->config('rnd',true);
		$conf = $this->config->item('rnd');
		$conf1 = $conf['perbuatan']['status'];
		
		//ada kodenya, jadi load config dulu
		$key = $this->input->post('key');
		$keysss = array();
		$keysss[] = $key; 
		if ($ss = array_search(ucwords($key), $conf1)) $keysss[] = $ss;	//key untuk status
		
		$limit = $this->input->post('limit');
		$offset = $this->input->post('offset') * $limit;
		$orderby = $this->input->post('orderby');
		$where = $this->input->post('where');
		
		$table_content = "";
		$row = 0;
		$data = $this->perbuatan_model->getApproved(
			$usrName, $keysss, $where, $limit, $offset, 
			$orderby? $orderby : array('perb_status'=>'desc'));
		$table_content = $this->load->view('perbuatan/users/table_content_AP', array(
			'data'=>$data,
			'status_options'=>$conf1,
			'usrAlias'=>$usrAlias,
			'usrName'=>$usrName
			), true); 	
		echo json_encode(array(
			'table_content'=>$table_content,
			'table_num_record'=> $key? $data->num_rows() : $this->perbuatan_model->count_record()
		));
	}
	
	function __search_RE(){
		$this->load->library('session');
		$usrName = $this->session->userdata('usrname');
		$usrAlias = md5($usrName);
		
		$this->load->model('perbuatan_model');
		$this->load->config('rnd',true);
		$conf = $this->config->item('rnd');
		$conf1 = $conf['perbuatan']['status'];
		
		//ada kodenya, jadi load config dulu
		$key = $this->input->post('key');
		$keysss = array();
		$keysss[] = $key; 
		if ($ss = array_search(ucwords($key), $conf1)) $keysss[] = $ss;	//key untuk status
		
		$limit = $this->input->post('limit');
		$offset = $this->input->post('offset') * $limit;
		$orderby = $this->input->post('orderby');
		$where = $this->input->post('where');
		
		$table_content = "";
		$row = 0;
		$data = $this->perbuatan_model->getRejected(
			$usrName, $keysss, $where, $limit, $offset, 
			$orderby? $orderby : array('perb_status'=>'desc'));
		$table_content = $this->load->view('perbuatan/users/table_content_RE', array(
			'data'=>$data,
			'status_options'=>$conf1,
			'usrAlias'=>$usrAlias,
			'usrName'=>$usrName
			), true); 	
		echo json_encode(array(
			'table_content'=>$table_content,
			'table_num_record'=> $key? $data->num_rows() : $this->perbuatan_model->count_record()
		));
	}
	
	function _translate_nav($nav, $userAlias){
		$nv = array();
		foreach ($nav as $title=>$value){
			$nv[$title] = array();
			foreach ($value as $item=>$val){
				$nv[$title][$item] = preg_replace("/(:user)/i",$userAlias, $val);
			}
		}
		return $nv;
	}
	
	/*********************************
	 * draft
	 *********************************/
	
	function draft(){
		$this->load->library('session');
		$usrAlias = md5($this->session->userdata('usrname'));
		
		$this->load->helper(array('html'));
		$this->load->config('rnd', true);
		$CONF = $this->config->item('rnd');

		//layout first
		$this->load->model('departemen_model');
		$layoutConf = $CONF['layout'];
		$layoutConf['left_content'] = array(
			'view'=>'template/horz_nav', 
			'view_data'=>array(
				'data'=>$usrAlias!=md5('admin')?
					$this->_translate_nav($CONF['nav']['users'],$usrAlias):
					$CONF['nav']['psdm'],
			) 
		);
		$layoutConf['right_content'] = array('view'=>'perbuatan/users/overview', 
			'view_data'=>array(
				'limit' => $CONF['search']['limit'],
				'usrAlias'=>$usrAlias
			));
		$this->initialize_layout($layoutConf);
		
		//page
		$pageConf = $CONF['page'];
		$pageConf['jscript_default'][] = 'users/perbuatan';
		$pageConf['jscript'] = $pageConf['jscript_default'];
		$pageConf['css'] = $pageConf['css_default'];
		$pageConf['template_view'] = 'template/2_layout';
		$this->initialize_page($pageConf);
		
		$this->finalize_view();
	}
	
	function _draft_search(){
		$this->load->library('session');
		$usrAlias = md5($this->session->userdata('usrname'));
		
		$this->load->model('perbuatan_model');
		$this->load->config('rnd',true);
		$conf = $this->config->item('rnd');
		$conf1 = $conf['perbuatan']['status'];
		
		//ada kodenya, jadi load config dulu
		$key = $this->input->post('key');
		$keysss = array();
		$keysss[] = $key; 
		if ($ss = array_search(ucwords($key), $conf1)) $keysss[] = $ss;	//key untuk status
		
		$limit = $this->input->post('limit');
		$offset = $this->input->post('offset') * $limit;
		$orderby = $this->input->post('orderby');
		$where = "perb_poster='$usrAlias' and perb_status='DR'";
		
		$table_content = "";
		$row = 0;
		$data = $this->perbuatan_model->select_last_entry($keysss, $where, $limit, $offset, $orderby? $orderby : array('perb_status'=>'desc'));
		$table_content = $this->load->view('perbuatan/users/table_content', 	array(
			'data'=>$data,
			'status_options'=>$conf1,
			'usrAlias'=>$usrAlias
			), true); 	
		echo json_encode(array(
			'table_content'=>$table_content,
			'table_num_record'=> $key? $data->num_rows() : $this->perbuatan_model->count_record()
		));
	}

	function add(){
		$this->load->library('session');
		$usrName = $this->session->userdata('usrname');
		$usrAlias = md5($usrName);
		
		$this->load->helper(array('html'));
		$this->load->config('rnd', true);
		$CONF = $this->config->item('rnd');

		//layout first
		$this->load->model('kota_model');
		$layoutConf = $CONF['layout'];
		$layoutConf['left_content'] = array(
			'view'=>'template/horz_nav', 
			'view_data'=>array('data'=>$this->_translate_nav($CONF['nav']['users'],$usrAlias)) );
		$layoutConf['right_content'] = array(
			'view'=>'perbuatan/users/add', 
			'view_data'=>array(
				'kota_options'=> $this->kota_model->select_all(array('kota_nama'=>'asc')),
				'usrAlias'=>$usrAlias,
				'usrName'=>$usrName
			)
		);
		$this->initialize_layout($layoutConf);
		
		//page
		$pageConf = $CONF['page'];
		$pageConf['jscript'] = array_merge(
			$pageConf['jscript_default'],
			array('users/perbuatan_add','datepicker','Swiff.Uploader','Fx.ProgressBar', 'FancyUpload',
				'utils/searchDialog'));
		
		$pageConf['css'] = array_merge($pageConf['css_default'], array('datepicker','FancyUpload'));
		$pageConf['template_view'] = 'template/2_layout';
		$this->initialize_page($pageConf);
		
		$this->finalize_view();
	}

	function _draft_save(){
		$inp = $this->input->post('inp');
		$lapor_nik = $this->input->post('lapor_nik');
		$res = true;
		
		//cek lapor nik
		$this->load->model(array('pelapor_model','karyawan_model'));
		$pelapor = (array)$this->pelapor_model->select_by_nik($lapor_nik)->row();
		if (!$pelapor){	//no pelapor, save it
			$karyData = (array)$this->karyawan_model->select_by_id($lapor_nik)->row();
			
			$res &= $this->pelapor_model->insert( array(
				'lapor_nik'=> $lapor_nik,
				'lapor_nama'=> $karyData['kary_nama']
			));
			if (!$res) { 
				echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->pelapor_model->mysql_innodb_error(mysql_errno())) );
				return;
			}
			$pelaporID = $this->pelapor_model->get_last_id();
		}
		else{
			$pelaporID = $pelapor['lapor_id'];
		}
		
		//save perbuatan
		$this->load->model('perbuatan_model');
		$this->load->library('session');
    	
		$res &= $this->perbuatan_model->insert( array(
//			'perb_id'=> $inp[],
			'perb_tgl_lapor'=> $inp[3],
			'perb_tempat_kejadian'=> $inp[5],
			'perb_tgl_kejadian'=> $inp[4],
			'perb_keterangan'=> $inp[8],
			'perb_status'=> 'DR',
			'perb_status_change'=> date("Y-m-d H:i:s", time()),
			'lapor_id'=> $pelaporID,
			'perb_poster'=> md5($this->session->userdata('usrname'))
		));
		if (!$res) { 
			echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->perbuatan_model->pelapor_alamat_model(mysql_errno())) );
			return;
		}
		$perbuatanID = $this->perbuatan_model->get_last_id();
		
		$this->load->model('perbuatan_detil_model');
		for($i=0; $i<count($inp[7]); $i+=2){
			$res &= $this->perbuatan_detil_model->insert(array(
				'perb_id'=> $perbuatanID,
				'kary_id'=> $inp[7][$i],
				'kary_jbt_id'=> $inp[7][$i+1],
				'detachiev_id'=> $inp[6],
			
				//@NOTE : saat ini diisi dengan nol, update saat approve
				'deperb_point'=> 0,
				'deperb_count'=> 0
			));
		}
		if (!$res) { 
			echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->perbuatan_detil_model->pelapor_alamat_model(mysql_errno())) );
			return;
		}
		
		//save the uploaded file to the database
		$this->load->model('perbuatan_bukti_model');
		$fields = array('perb_dok_file_size','perb_dok_file_name','perb_dok_file_type','perb_dok_content','perb_id');
		foreach($inp[9] as $ff){
			$path = "system/cache/$ff";
			$value = array();
			$fileSize =  filesize ($path);
			
			$value[] = $fileSize;
			$value[] = addslashes(preg_replace('/(.*)\[/i','', str_replace(']','',$ff)));
			
			$info = @getimagesize($path);
			$value[] = $info['mime'];
			$value[]  = fread( fopen($path, "r"), $fileSize ); 
			$value[] = $perbuatanID;
			
			$res &= $this->perbuatan_bukti_model->insert(array_combine($fields, $value));
			
			//delete file
			@unlink($path);
		}
		
		$this->load->library('session');
		$usrAlias = md5( $this->session->userdata('usrname') );
		echo json_encode(array(
			'error'=>!$res,
			'msg'=>"Proses simpan selesai",'location'=>site_url(array('users',$usrAlias,'perbuatan','draft'))));
	}
	
	function edit($id){
		$this->load->library('session');
		$usrName = $this->session->userdata('usrname');
		$usrAlias = md5($usrName);
		
		//load the perbuatan data
		$this->load->model(array('perbuatan_model','perbuatan_detil_model',
			'perbuatan_bukti_model','pelapor_model', 'karyawan_model', 'karyawan_history_jabatan_model'));
		$data = array();
		$perbData = (array) $this->perbuatan_model->select_by_id($id)->row();
		$buktiperbData = $this->perbuatan_bukti_model->select_by_perbuatan($perbData['perb_id']);
		$deperbData = $this->perbuatan_detil_model->select_by_perbuatan($perbData['perb_id']);
		$laporData = (array)$this->pelapor_model->select_by_id($perbData['lapor_id'])->row();
		
		//insert to variable
		$data['perbData'] = $perbData;
		$data['laporData'] = $laporData;
		foreach($deperbData->result_array() as $res){
			$data['deperbData'][] = $res;
		}
		foreach($buktiperbData->result_array() as $res){
			$data['buktiperbData'][] = $res;
		}
		
		//layout the view
		$this->load->helper(array('html'));
		$this->load->config('rnd', true);
		$CONF = $this->config->item('rnd');

		//layout first
		$this->load->model('kota_model');
		$layoutConf = $CONF['layout'];
		$layoutConf['left_content'] = array(
			'view'=>'template/horz_nav', 
			'view_data'=>array(
				'data'=>$this->_translate_nav($CONF['nav']['users'],$usrAlias),
			)
		);
		$layoutConf['right_content'] = array(
			'view'=>'perbuatan/users/edit', 
			'view_data'=>array_merge(array(
				'kota_options'=> $this->kota_model->select_all(array('kota_nama'=>'asc')),
				'jenis_options'=>$CONF['achievement']['jenis_options'],
				'tingkat_options'=>array_merge(
					$CONF['detachievement']['tingkat_options']['PE'],
					$CONF['detachievement']['tingkat_options']['PR']),
				'usrAlias'=>$usrAlias
			),$data)
		);
		$this->initialize_layout($layoutConf);
		
		//page
		$pageConf = $CONF['page'];
		$pageConf['jscript'] = array_merge(
			$pageConf['jscript_default'],
			array('users/perbuatan_edit','datepicker','Swiff.Uploader','Fx.ProgressBar', 'FancyUpload',
				'utils/searchDialog'));
		
		$pageConf['css'] = array_merge($pageConf['css_default'], array('datepicker','FancyUpload'));
		$pageConf['template_view'] = 'template/2_layout';
		$this->initialize_page($pageConf);
		
		$this->finalize_view();
	}
	
	function _draft_update(){
		$inp = $this->input->post('inp');
		$perbuatanID = $this->input->post('perb_id');
		$pelaporID = $inp[0][0];
		$res = true;
		
		//save perbuatan
		$this->load->model('perbuatan_model');
		$this->load->library('session');
    	
		$res &= $this->perbuatan_model->update(array('perb_id'=>$perbuatanID), array(
//			'perb_id'=> $inp[],
			'perb_tgl_lapor'=> $inp[3],
			'perb_tempat_kejadian'=> $inp[5],
			'perb_tgl_kejadian'=> $inp[4],
			'perb_keterangan'=> $inp[8],
			'perb_status'=> 'DR',
			'perb_status_change'=> date("Y-m-d H:i:s", time()),
			'lapor_id'=> $pelaporID,
			'perb_poster'=> md5($this->session->userdata('usrname'))
		));
		if (!$res) { 
			echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->perbuatan_model->pelapor_alamat_model(mysql_errno())) );
			return;
		}
		
		//insert pelaku baru
		$in_array = '';
		$this->load->model('perbuatan_detil_model');
		for($i=0; $i<count($inp[7]); $i+=2){
			$opt = array('insert','update');
			$ind = $this->perbuatan_detil_model->is_exist($perbuatanID, $inp[7][$i])? 1 : 0;
			$res &= $this->perbuatan_detil_model->{$opt[$ind]}(
				array(
					'perb_id'=>$perbuatanID,
					'kary_id'=>$inp[7][$i]),
				array(
					'perb_id'=> $perbuatanID,
					//'kary_id'=> $inp[7][$i],
					'kary_jbt_id'=> $inp[7][$i+1],
					'detachiev_id'=> $inp[6],
				
					//@NOTE : saat ini diisi dengan nol, update saat approve
					'deperb_point'=> 0,
					'deperb_count'=> 0
			));
			$in_array = ($in_array? ',':'')."'".$inp[7][$i]."'";
		}
		//delete that not in array
		$this->perbuatan_detil_model->delete("perb_id='$perbuatanID' AND kary_id NOT IN ($in_array)");
		
		if (!$res) { 
			echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->perbuatan_detil_model->pelapor_alamat_model(mysql_errno())) );
			return;
		}
		
		//delete uploaded file that not checked
		$this->load->model('perbuatan_bukti_model');
		$uploaded = false;
		foreach($inp['uploaded'] as $up){
			$uploaded .= ($uploaded? ",":"")."'$up'";
		}
		$res &= $this->perbuatan_bukti_model->delete("perb_id = '$perbuatanID' AND perb_dok_id NOT IN ($uploaded)");
		
		if (!$res) { 
			echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->perbuatan_bukti_model->pelapor_alamat_model(mysql_errno())) );
			return;
		}
		
		//save the uploaded file to the database
		if (isset($inp[9])){
			$fields = array('perb_dok_file_size','perb_dok_file_name','perb_dok_file_type','perb_dok_content','perb_id');
			foreach($inp[9] as $ff){
				$path = "system/cache/$ff";
				$value = array();
				$fileSize =  filesize ($path);
				
				$value[] = $fileSize;
				$value[] = addslashes(preg_replace('/(.*)\[/i','', str_replace(']','',$ff)));
				
				$info = @getimagesize($path);
				$value[] = $info['mime'];
				$value[]  = fread( fopen($path, "r"), $fileSize ); 
				$value[] = $perbuatanID;
				
				$res &= $this->perbuatan_bukti_model->insert(array_combine($fields, $value));
				
				//delete file
				@unlink($path);
			}
		}
		echo json_encode(array(
			'error'=>!$res,
			'msg'=>"Proses simpan selesai",'location'=>site_url(array('users',$usrAlias,'perbuatan','draft'))));
	}
	
	function _delete($id){
		$this->load->model(array('perbuatan_model','perbuatan_detil_model','perbuatan_bukti_model'));
		$res = $this->perbuatan_bukti_model->delete(array('perb_id' => $id));
		$res &= $this->perbuatan_detil_model->delete(array('perb_id' => $id));
		$res &= $this->perbuatan_model->delete(array('perb_id' => $id));
		$msg = $res? "Proses hapus selesai" : "Proses hapus gagal, ".$this->perbuatan_model->mysql_innodb_error(mysql_errno());
		echo json_encode(array('error'=>!$res,'msg'=>$msg));
	}
	
	/*********************************
	 * persetujuan
	 *********************************/
	
	function persetujuan($func=false, $a=false, $b=false, $c=false){
		$func = "_persetujuan_$func";
		if ( method_exists($this, $func) ) {
	    	call_user_func_array( array($this, $func), array($a,$b,$c));
	    }
	}
	
	function _persetujuan($func=false, $a=false, $b=false, $c=false){
		$func = "__persetujuan_$func";
		if ( method_exists($this, $func) ) {
	    	call_user_func_array( array($this, $func), array($a,$b,$c));
	    }
	}
	
	/**
	 * @deprecated
	 */
	function _persetujuan_index(){
		$this->load->library('session');
		$usrAlias = md5($this->session->userdata('usrname'));
		
		$this->load->helper(array('html'));
		$this->load->config('rnd', true);
		$CONF = $this->config->item('rnd');

		//layout first
		$this->load->model('departemen_model');
		$layoutConf = $CONF['layout'];
		$layoutConf['left_content'] = array(
			'view'=>'template/horz_nav', 
			'view_data'=>array(
				'data'=>$this->_translate_nav($CONF['nav']['users'],$usrAlias)
			) 
		);
		$layoutConf['right_content'] = array('view'=>'perbuatan/users/persetujuan/overview', 
			'view_data'=>array(
				'limit' => $CONF['search']['limit'],
				'usrAlias'=>$usrAlias
			));
		$this->initialize_layout($layoutConf);
		
		//page
		$pageConf = $CONF['page'];
		$pageConf['jscript_default'][] = 'users/perbuatan_persetujuan';
		$pageConf['jscript'] = $pageConf['jscript_default'];
		$pageConf['css'] = $pageConf['css_default'];
		$pageConf['template_view'] = 'template/2_layout';
		$this->initialize_page($pageConf);
		
		$this->finalize_view();
	}
	
	function _persetujuan_search(){
		$this->load->library('session');
		$usrName = $this->session->userdata('usrname');
		$usrAlias = md5($usrName);
		
		$this->load->model('perbuatan_model');
		$this->load->config('rnd',true);
		$conf = $this->config->item('rnd');
		$conf1 = $conf['perbuatan']['status'];
		
		//ada kodenya, jadi load config dulu
		$key = $this->input->post('key');
		$keysss = array();
		$keysss[] = $key; 
		if ($ss = array_search(ucwords($key), $conf1)) $keysss[] = $ss;	//key untuk status
		
		$limit = $this->input->post('limit');
		$offset = $this->input->post('offset') * $limit;
		$orderby = $this->input->post('orderby');
		$where = $this->input->post('orderby');
		
		$table_content = "";
		$row = 0;
		$data = $this->perbuatan_model->getRequestApproval(
			$usrName, $keysss, $where, $limit, $offset, 
			$orderby? $orderby : array('perb_status'=>'desc'));
		$table_content = $this->load->view('perbuatan/users/persetujuan/table_content', array(
			'data'=>$data,
			'status_options'=>$conf1,
			'usrAlias'=>$usrAlias,
			'usrName'=>$usrName
			), true); 	
		echo json_encode(array(
			'table_content'=>$table_content,
			'table_num_record'=> $key? $data->num_rows() : $this->perbuatan_model->count_record()
		));
	}
	
	function __persetujuan_reject(){
		$inp = $this->input->post('inp');
		$inp = $inp['RE'];
		$res = true;

		
		$this->load->model('perbuatan_detil_model');
		$this->load->model('bap_model');
		$this->load->model('detachievement_model');
		$perb_id = "";
		
		//cek jenis perbuatan
		//$detachi = $this->detachievement_model->select_by_id();
		
		//simpan bap, untuk tiap karyawan
		$deperbData = $this->perbuatan_detil_model->select_by_perbuatan($inp['perb_id']);
		foreach($deperbData->result_array() as $row){
			$res &= $this->bap_model->insert(array(
				'bap_tgl'=>date('Y-m-d H:i:s', time()),
				'bap_pembuat_kary_id'=>$inp['pembuat']['kary_id'],
				'bap_pembuat_kary_jbt_id'=>$inp['pembuat']['jbt_id'],
        		'bap_pembuat_keterangan'=>$inp['keterangan'],
        		'bap_status'=>'RR',
				'perb_id'=>$row['perb_id'],
        		'kary_id'=>$row['kary_id'],
        		'kary_jbt_id'=>$row['kary_jbt_id']
			));
			$perb_id = $row['perb_id'];
			if (!$res) { 
				echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->perbuatan_detil_model->mysql_innodb_error(mysql_errno())) );
				exit;
			}
		}
		
		//tidak perlu simpan saksi, karena laporan perbuatan ditolak
		
		//sampe sini brarti ndak ada error
		//update stus laporan perbuatannya
		$this->_updateStatus($inp['perb_id'],'RE');
			
		//send message
		$this->load->library('session');
		$usrName = $this->session->userdata('usrname');
		$usrAlias = md5($usrName);
		echo json_encode( array( 'error'=>false, 'url'=>site_url(array('users',$usrAlias,'perbuatan'))) );
	}
	
	function __persetujuan_approve(){
		$inp = $this->input->post('inp');
		$inp = $inp['AP'];
		$res = true;

		$this->load->model('perbuatan_detil_model');
		$this->load->model('bap_model');
		$this->load->model('detachievement_model');
		$deperbData = $this->perbuatan_detil_model->select_by_perbuatan($inp['perb_id']);
		$perb_id = "";
		
		//simpan bap, untuk tiap karyawan
		foreach($deperbData->result_array() as $row){
			//cek jenis perbuatan
			$detachiev = (array)$this->detachievement_model->select_by_id($row['detachiev_id'])->row();
			
			$res &= $this->bap_model->insert(array(
				'bap_tgl'=>date('Y-m-d H:i:s', time()),
				'bap_pembuat_kary_id'=>$inp['pembuat']['kary_id'],
				'bap_pembuat_kary_jbt_id'=>$inp['pembuat']['jbt_id'],
        		'bap_pembuat_keterangan'=>$inp['keterangan'],
        		'bap_status'=>'RS',
				'perb_id'=>$row['perb_id'],
        		'kary_id'=>$row['kary_id'],
        		'kary_jbt_id'=>$row['kary_jbt_id']
			));
			$perb_id = $row['perb_id'];
			if (!$res) { 
				echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->bap_model->mysql_innodb_error(mysql_errno())) );
				exit;
			}
			
			if ($detachiev['achiev_jenis']=="PR"){
				$this->__persetujuan_approve_prestasi($perb_id);
			}
			else if ($detachiev['achiev_jenis']=="PE"){
				$this->__persetujuan_approve_pelanggaran($perb_id);
			}
		}
		
		//send message
		$this->load->library('session');
		$usrName = $this->session->userdata('usrname');
		$usrAlias = md5($usrName);
		echo json_encode( array( 'error'=>false, 'url'=>site_url(array('users',$usrAlias,'perbuatan'))) );
	}
	
	function __persetujuan_approve_prestasi($perb_id){
		$inp = $this->input->post('inp');
		$inp = $inp['AP'];
		$res=true;
		
		$this->load->model(array('bap_model','bap_sign_model'));
		$bapData = $this->bap_model->select_by_perbID($perb_id);
		
		//prestasi tidak perlu persetujuan dari siapapun pelapor maupun pelaku,
		//langksung diaktifkan
		foreach($bapData->result_array() as $row){
			$this->bap_sign_model->insert(array(
				'kary_id'=>$row['kary_id'],
				'bap_id'=>$row['bap_id'],
				'bap_sign_type'=>'AC',
				'bap_sign_signing'=>md5($row['kary_id'])		//langsung beri ttd
			));
			
			//simpan saksi
			if (isset($inp['pelapor']) && $inp['pelapor']!=""){
				$this->bap_sign_model->insert(array(
					'kary_id'=>$inp['pelapor'],
					'bap_id'=>$row['bap_id'],
					'bap_sign_type'=>'WT',
					'bap_sign_signing'=>md5($inp['pelapor'])		//langsung beri ttd
				));
				if (!$res) { 
					echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->bap_sign_model->mysql_innodb_error(mysql_errno())) );
					exit;
				}
			}
			if (isset($inp['saksi'])){
				foreach($inp['saksi'] as $saksi){
					if (!$saksi[0] || $saksi[0]=="") continue;
					$this->bap_sign_model->insert(array(
					'kary_id'=>$saksi[0],
					'bap_id'=>$row['bap_id'],
					'bap_sign_type'=>'WT',
					'bap_sign_signing'=>md5($saksi[0])		//langsung beri ttd
					));
				}
				if (!$res) { 
					echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->bap_sign_model->mysql_innodb_error(mysql_errno())) );
					exit;
				}
			}
			
			//buat notifikasi ke pelapor
			$this->load->helper('notification');
			$this->_updateStatus($inp['perb_id'],'AP');
			
			//buat notifikasi ke pelaku
			$this->load->model('bap_sign_model');
			$this->bap_model->update(
				array('bap_id'=>$row['bap_id']), 
				array('bap_status'=>'SA',
					'bap_status_change'=>date("Y-m-d H:i:s",time())));
			createBAPNotification($row['bap_id'], 'SA');
			
			//insert penilaian
			$this->load->helper('penilaian');
			insertPointPenilaian($row['bap_id']);
		}
	}
	
	function __persetujuan_approve_pelanggaran($perb_id){
		$inp = $this->input->post('inp');
		$inp = $inp['AP'];
		$res=true;
		
		$bapData = $this->bap_model->select_by_perbID($perb_id); 
		$this->load->model('bap_sign_model');
		foreach($bapData->result_array() as $row){
			//simpan pelaku
			$this->bap_sign_model->insert(array(
				'kary_id'=>$row['kary_id'],
				'bap_id'=>$row['bap_id'],
				'bap_sign_type'=>'AC'
			));
			
			//simpan saksi
			if (isset($inp['pelapor']) && $inp['pelapor']!=""){
				$this->bap_sign_model->insert(array(
					'kary_id'=>$inp['pelapor'],
					'bap_id'=>$row['bap_id'],
					'bap_sign_type'=>'WT'
				));
				if (!$res) { 
					echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->bap_sign_model->mysql_innodb_error(mysql_errno())) );
					exit;
				}
			}
			if (isset($inp['saksi'])){
				foreach($inp['saksi'] as $saksi){
					if (!$saksi[0] || $saksi[0]=="") continue;
					$this->bap_sign_model->insert(array(
					'kary_id'=>$saksi[0],
					'bap_id'=>$row['bap_id'],
					'bap_sign_type'=>'WT'
					));
				}
				if (!$res) { 
					echo json_encode( array( 'error'=>!$res, 'msg'=>"Proses simpan gagal, ".$this->bap_sign_model->mysql_innodb_error(mysql_errno())) );
					exit;
				}
			}
		}
		
		//sampe sini brarti ndak ada error
		//update stus laporan perbuatannya dan buat notifikasi untuk saksi
		$this->_updateStatus($inp['perb_id'],'AP');
	}
	
	function _updateStatus($perbID, $status){
		$this->load->model('perbuatan_model');
		$res = $this->perbuatan_model->update(array('perb_id'=>$perbID),  array(
			'perb_status' => $status, 
			'perb_status_change'=>date("Y-m-d H:i:s",time())));
		
		//create notification
		$this->load->helper('notification');
		createNotification($perbID, $status);
		return $res;
	}
	
	function _persetujuan_detailView($status, $perb_id){
		$this->load->library('session');
		$usrName = $this->session->userdata('usrname');
		$usrAlias = md5($usrName);
		
		//load the perbuatan data
		$this->load->model(array('perbuatan_model','perbuatan_detil_model',
			'perbuatan_bukti_model','pelapor_model', 'karyawan_model', 'karyawan_history_jabatan_model'));
		$data = array();
		$perbData = (array) $this->perbuatan_model->select_by_id($perb_id)->row();
		$buktiperbData = $this->perbuatan_bukti_model->select_by_perbuatan($perbData['perb_id']);
		$deperbData = $this->perbuatan_detil_model->select_by_perbuatan($perbData['perb_id']);
		$laporData = (array)$this->pelapor_model->select_by_id($perbData['lapor_id'])->row();
		
		//insert to variable
		$data['perbData'] = $perbData;
		$data['laporData'] = $laporData;
		foreach($deperbData->result_array() as $res){
			$data['deperbData'][] = $res;
		}
		foreach($buktiperbData->result_array() as $res){
			$data['buktiperbData'][] = $res;
		}
		
		//layout the view
		$this->load->helper(array('html'));
		$this->load->config('rnd', true);
		$CONF = $this->config->item('rnd');

		//layout first
		$this->load->model('kota_model');
		$layoutConf = $CONF['layout'];
		$layoutConf['left_content'] = array(
			'view'=>'template/horz_nav', 
			'view_data'=>array(
				'data'=>$this->_translate_nav($CONF['nav']['users'],$usrAlias),
			)
		);
		$layoutConf['right_content'] = array(
			'view'=>"perbuatan/users/detailView_$status",
			'view_data'=>array_merge(array(
				'kota_options'=> $this->kota_model->select_all(array('kota_nama'=>'asc')),
				'jenis_options'=>$CONF['achievement']['jenis_options'],
				'tingkat_options'=>array_merge(
					$CONF['detachievement']['tingkat_options']['PE'],
					$CONF['detachievement']['tingkat_options']['PR']),
				'usrAlias'=>$usrAlias,
				'usrName'=>$usrName
			),$data)
		);
		$this->initialize_layout($layoutConf);
		
		//page
		$pageConf = $CONF['page'];
		$pageConf['jscript'] = array_merge($pageConf['jscript_default'],
			array("users/perbuatan/detailView_$status",'datepicker','Swiff.Uploader',
				'Fx.ProgressBar', 'utils/searchDialog',
				'mooEditable/MooEditable', 'mooEditable/MooEditable.UI.MenuList',
				'mooEditable/MooEditable.Extras',
				//'FancyUpload',
				//'mooEditable/localization/MooEditable.English.US.example'
				));
		
		$pageConf['css'] = array_merge($pageConf['css_default'], 
			array('datepicker','FancyUpload', 'mooEditable/MooEditable', 
				'MooEditable/MooEditable.Extras','MooEditable/MooEditable.SilkTheme'));
		$pageConf['template_view'] = 'template/2_layout';
		$this->initialize_page($pageConf);
		
		$this->finalize_view();
	}
	
	/*********************************
	 * misc
	 *********************************/
	
	function _getJabatanCombo($kary_id){
		$this->load->model('karyawan_history_jabatan_model');
		$rest = $this->karyawan_history_jabatan_model->getActive($kary_id);
		$cc = "";
		if ($rest->num_rows()>1) $cc .= "<option>--- pilih ---";
		foreach($rest->result_array() as $row){
			$cc .= "<option value='". $row['kary_jbt_id'] ."'>". $row['jbt_nama']." [".$row['dep_nama']."]" ."</option>";
		}
		$this->finalize_view_str($cc);
	}
	
	function _loadImage($image){
		$this->load->model('perbuatan_bukti_model');
		$img = (array)$this->perbuatan_bukti_model->select_by_id($image)->row();
		header("Content-type: ".$img['perb_dok_file_type']);
		print $img['perb_dok_content'];
	}
}
/* End of file users/perbuatan.php */
/* Location: ./system/application/controllers/users/perbuatan.php */